﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PropertyManagment.config;
using PropertyManagment.entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace PropertyManagment.mapper.impl {

    public class SysUserMapperImpl : BaseMapperImpl<SysUser>, SysUserMapper {

        private readonly DbSet<SysUserRole> sysUserRoles;
        private readonly DbSet<SysRoleMenu> sysRoleMenus;
        public SysUserMapperImpl(AppDbContext context) : base(context) {
            sysUserRoles = context.Set<SysUserRole>();
            sysRoleMenus = context.Set<SysRoleMenu>();
        }

        public List<SysUser> getByRoleId(long roleId) {
            var query = from ur in sysUserRoles
                        where ur.role_id == roleId
                        select ur.user_id;
            List<SysUser> sysUser = selectBatchIds(query.ToList()).ToList();
            return sysUser;
        }

        public List<SysUser> getByMenuId(long menuId) {
            var query = from ur in sysUserRoles
                        join rm in sysRoleMenus on ur.role_id equals rm.role_id
                        join u in dbSet on ur.user_id equals u.id
                        where rm.menu_id == menuId
                        select u;

            List<SysUser> list = query.Distinct().ToList();
            return list;
        }

        public SysUser getByUsernameAndPassword(string username, string password) {
            List<SysUser> sysUser = dbSet.Where<SysUser>(p => p.username == username && p.password == password).ToList();
            if (sysUser.Count > 0) {
                return sysUser[0];
            } else {
                return null;
            }
        }
    }
}
